package com.atguigu.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.model.acl.User;
import com.atguigu.yygh.common.model.user.UserInfo;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信操作的接口
 */
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 微信扫描后回调的方法
     * @param code
     * @param state
     * @return
     */
    @GetMapping("callback")
    public String collback(String code,String state){
        //第一步:获取授权临时票据和Code
        System.out.println("微信授权服务器回调。。。。。。");
        System.out.println("state = " + state);
        System.out.println("code = " + code);

        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)){
            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }

        //第二步:拿着code和微信id与密钥，请求微信固定地址，得到两个值
        // 使用code和appid以及appscrect换取access_token
        // %s占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        try {
            // 使用httpclient请求这个地址
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo->>>"+accessTokenInfo);

            //从accessTokenInfo获取两个值  openid、access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String accessToken = jsonObject.getString("access_token");
            String openId = jsonObject.getString("openid");

            //判断数据库是否存在扫描人信息
            UserInfo userInfo =  userInfoService.selectWxInfoOpenId(openId);
            if (null==userInfo){

                //第三步 拿着openid、access_token 请求微信地址，得到扫码人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openId);
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("扫码人信息->>>"+resultUserInfo);


                JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);
                //解析用户信息
                String nickname = resultUserInfoJson.getString("nickname");
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                //把用户信息添加到数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openId);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            //返回name和token字符串
            Map<String, Object> map = new HashMap<>(16);
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //判断userInfo中是否有手机号，如果为空，就返回openid
            //如果不为空，openid返回为空
            //前端判断:如果openid不为空，绑定手机号 如果为空 不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }

            //使用JWT生成Token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"));

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 1.生成微信扫描二维码
     * 2.返回生成二维码需要的参数
     * @return 参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result<Map<String,Object>> genQrConnect(){
        Map<String,Object> map = new HashMap<>(16);
        try {
            String redirectUri = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            URLEncoder.encode(redirectUri,"utf-8");
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            map.put("redirect_uri", redirectUri);
            map.put("state", System.currentTimeMillis()+"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return Result.ok(map);
    }
}

